package cn.dancepeak.aop;


import cn.dancepeak.jwt.JwtUtil;
import cn.dancepeak.jwt.Payload;
import cn.dancepeak.log.domain.Log;
import cn.dancepeak.log.mapper.LogMapper;
import cn.dancepeak.system.domain.Login;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Date;

@Aspect
@Component
public class LogAspect {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private LogMapper logMapper;
    // 指定annotation切点表达式，查找@Log注解
    @Around("@annotation(cn.dancepeak.anno.Log)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        // 1.开始操作时间
        LocalDateTime now = LocalDateTime.now();
        // 2.设置操作类名
        String className = pjp.getTarget().getClass().getName();
        // 3.操作方法名
        String methodName = pjp.getSignature().getName();
        // 4.方法参数
        Object[] args = pjp.getArgs() == null?null:pjp.getArgs();
        String methodParams = Arrays.toString(args);
        // 5.执行目标方法以及获取到方法返回值
        long beginTime = System.currentTimeMillis();
        Object result = pjp.proceed();
        long endTime = System.currentTimeMillis();
        // 6.操作耗时
        Long costTime = endTime - beginTime;
        // 7.操作Ip
        String ip = request.getRemoteAddr();
        // 8.记录操作日志，因为没有做登录，所以操作Id和操作用户名称写死
        //拿到前端的token  转成jwt串
        String token = request.getHeader("token");
        Payload payload = JwtUtil.parseJwtToken(token);
        //拿到串里的基本信息
        Login logininfo = payload.getLogininfo();
        Long userId = logininfo.getId();
        String username = logininfo.getUsername();

        Log log = new Log(null, userId, username, new Date(),
                className, methodName,methodParams, result==null?null:result.toString(),
                costTime, ip);
        logMapper.insert(log);
        return result;
    }
}
